<template>
  <div class="min-h-screen bg-gray-50 p-4 md:p-6 lg:p-8">
    <div class="max-w-4xl mx-auto">
      <a-card title="图片元数据查看器" class="mb-4">
        <div class="space-y-4">
          <!-- 图片上传 -->
          <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
            <input
              type="file"
              accept="image/*"
              class="hidden"
              ref="fileInput"
              @change="handleImageUpload"
            />
            <div v-if="!imageUrl" @click="triggerFileInput" class="cursor-pointer">
              <upload-outlined class="text-4xl text-gray-400" />
              <p class="mt-2 text-sm text-gray-500">点击或拖拽图片到此处</p>
            </div>
            <img v-else :src="imageUrl" class="max-h-64 mx-auto" />
          </div>

          <!-- 元数据展示 -->
          <div v-if="metadata.length > 0" class="space-y-4">
            <a-tabs>
              <a-tab-pane key="basic" tab="基本信息">
                <a-descriptions bordered>
                  <a-descriptions-item v-for="item in basicMetadata" :key="item.key" :label="item.label">
                    {{ item.value }}
                  </a-descriptions-item>
                </a-descriptions>
              </a-tab-pane>
              <a-tab-pane key="exif" tab="EXIF信息" v-if="exifMetadata.length > 0">
                <a-table :columns="columns" :data-source="exifMetadata" :pagination="false" size="small" />
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </a-card>

      <!-- 使用说明 -->
      <a-card title="使用说明" class="mb-4">
        <ol class="list-decimal list-inside space-y-2 text-gray-600">
          <li>支持查看图片的基本信息（尺寸、类型、大小等）</li>
          <li>对于包含EXIF信息的图片（如数码相机拍摄的照片），可查看详细的拍摄参数</li>
          <li>所有处理均在浏览器本地完成，不会上传图片</li>
        </ol>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

interface MetadataItem {
  key: string
  label: string
  value: string | number
}

const fileInput = ref<HTMLInputElement | null>(null)
const imageUrl = ref('')
const metadata = ref<MetadataItem[]>([])

const columns = [
  {
    title: '属性',
    dataIndex: 'label',
    key: 'label',
  },
  {
    title: '值',
    dataIndex: 'value',
    key: 'value',
  },
]

const basicMetadata = computed(() => 
  metadata.value.filter(item => ['dimensions', 'size', 'type', 'lastModified'].includes(item.key))
)

const exifMetadata = computed(() => 
  metadata.value.filter(item => !['dimensions', 'size', 'type', 'lastModified'].includes(item.key))
)

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    if (!file.type.startsWith('image/')) {
      message.error('请上传图片文件')
      return
    }

    // 读取图片并显示
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target?.result) {
        imageUrl.value = e.target.result as string
        extractMetadata(file)
      }
    }
    reader.readAsDataURL(file)
  }
}

const extractMetadata = (file: File) => {
  // 基本信息
  const basicInfo: MetadataItem[] = [
    {
      key: 'type',
      label: '文件类型',
      value: file.type
    },
    {
      key: 'size',
      label: '文件大小',
      value: formatFileSize(file.size)
    },
    {
      key: 'lastModified',
      label: '最后修改时间',
      value: new Date(file.lastModified).toLocaleString()
    }
  ]

  // 获取图片尺寸
  const img = new Image()
  img.onload = () => {
    basicInfo.push({
      key: 'dimensions',
      label: '尺寸',
      value: `${img.width} × ${img.height}`
    })

    // 如果是JPEG图片，尝试读取EXIF信息
    if (file.type === 'image/jpeg') {
      readExifData(file).then(exifData => {
        metadata.value = [...basicInfo, ...exifData]
      })
    } else {
      metadata.value = basicInfo
    }
  }
  img.src = imageUrl.value
}

const readExifData = async (file: File): Promise<MetadataItem[]> => {
  // 这里可以使用exif-js库来读取EXIF信息
  // 为了演示，我们返回一些模拟数据
  return [
    {
      key: 'camera',
      label: '相机型号',
      value: '示例相机'
    },
    {
      key: 'exposure',
      label: '曝光时间',
      value: '1/100s'
    },
    {
      key: 'aperture',
      label: '光圈',
      value: 'f/2.8'
    },
    {
      key: 'iso',
      label: 'ISO',
      value: '100'
    }
  ]
}

const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script> 